package com.taotao.order.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.taotao.cart.service.CartService;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.util.CookieUtils;
import com.taotao.order.pojo.OrderInfo;
import com.taotao.order.service.OrderService;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbUser;
import com.taotao.sso.service.UserLoginService;

/**
 * 订单处理的Controller
 * @title OrderController
 * <p>description</p>
 * <p>company: www.itheima.com</p>
 * @author 天火
 * @version 1.0
 */
@Controller
public class OrderController {
	
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private CartService cartService;
	
	@Value("${TT_TOKEN_KEY}")
	private String TT_TOKEN_KEY;
	

	/**
	 * url:/order/order-cart
	 * 参数：没有参数，但需要用户的Id，从cookie中获取到token，调用sso的服务获取用户的Id
	 * 返回值：逻辑视图(订单的确定页面)
	 */
	@RequestMapping("/order/order-cart")
	public String showView(HttpServletRequest request) {
		/*//1.从cookie中获取用户的信息
		String token = CookieUtils.getCookieValue(request, TT_TOKEN_KEY);
		if(StringUtils.isNoneBlank(token)) {
			//2.调用SSO服务获取用户的信息
			TaotaoResult result = userLoginService.getUserBytoken(token);
			if(result.getStatus()==200) {
				//3.必须是用户登录才有提示
				//4.展示用户的地址 根据用户的iD；来查询用户地址
				//5.展示支付方式，从数据库中获取数据 静态方式
				//6.调用购物车服务获取购物车的商品列表
				TbUser user = (TbUser) result.getData();
				List<TbItem> List = cartService.getCartList(user.getId());
				//7.将列表 展示到页面中 (使用model设置)
				request.setAttribute("cartList", List);
			}
		}*/
		TbUser user = (TbUser) request.getAttribute("UserInfo");
		List<TbItem> List = cartService.getCartList(user.getId());
		//7.将列表 展示到页面中 (使用model设置)
		request.setAttribute("cartList", List);
		
		return "order-cart";
	}
	
	/**
	 * url:/order/create
	 * 参数使用OrderInfo来接收
	 * 返回值：逻辑视图
	 * @param info
	 * @return
	 */
	@RequestMapping(value="/order/create",method=RequestMethod.POST)
	public String createOrder(OrderInfo info, HttpServletRequest request) {
		//1.引入服务
		//2.注入服务
		//3.调用
		//查询用户信息，设置到info中
		TbUser user = (TbUser) request.getAttribute("UserInfo");
		info.setUserId(user.getId());
		info.setBuyerNick(user.getUsername());
		TaotaoResult result = orderService.createOrder(info);
		request.setAttribute("orderId", result.getData());
		request.setAttribute("payment", info.getPayment());
		DateTime dateTime = new DateTime();
		DateTime dateTime2 = dateTime.plusDays(3);
		request.setAttribute("date", dateTime2.toString("yyyy-MM-dd"));
		return "success";
	}
	
	
	
	
}
